import json
import boto3
import random
import time
from boto3.dynamodb.conditions import Key, Attr


def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    visitors_table = dynamodb.Table('visitors')
    rekognition = boto3.client('rekognition')
    sns = boto3.client('sns')
    # s3 = boto3.resource('s3')
    s3_client = boto3.client('s3')
    # TODO implement
    try:
        data = event["body"]
        data = data.split("&")
        name = data[0][5:]
        phoneNumber = data[1][12:]

        # upload to collection and get faceId
        rekoResponse = rekognition.index_faces(
            Image={"S3Object":
                       {"Bucket": 'columbia-hw2-tt2756',
                        "Name": 'test.jpg'}},
            ExternalImageId=name,
            CollectionId="faceCollection")
        if len(rekoResponse['FaceRecords'][0]) != 0:
            faceId = rekoResponse['FaceRecords'][0]['Face']['FaceId']
        else:
            return 'error! not a human face'

        # if known, upload a photo in s3 to collection, get a response of faceId. then store them in DB2
        photo = time.strftime("%Y-%m-%d_%H.%M.%S", time.localtime()) + '.jpg'
        # visitors_table_response = visitors_table.scan(
        #     FilterExpression=Attr('faceId').eq(faceId)
        # )
        # if len(visitors_table_response["Items"]):
        #     people = visitors_table_response["Items"][0]
        #     photos = people['photo']
        #     photos += ',' + newPhoto
        # else:
        #     photos = newPhoto

        visitors_table.put_item(
            Item={
                'name': name,
                'phoneNumber': phoneNumber,
                'faceId': faceId,
                'photo': photo,
            }
        )

        # move test.jpg to {faceId} folder
        # copy_source = {
        #     'Bucket': 'columbia-hw2-tt2756',
        #     'Key': 'test.jpg'
        # }
        # s3.meta.client.copy(copy_source, 'columbia-hw2-tt2756', f'{faceId}/{photo}')
        s3_move_response = s3_client.copy_object(
            Bucket='columbia-hw2-tt2756',
            CopySource='columbia-hw2-tt2756/test.jpg',
            Key=f'{faceId}/{photo}',
        )

        # delete test.jpg
        s3_response = s3_client.delete_object(
            Bucket='columbia-hw2-tt2756',
            Key='test.jpg',
        )

        # generate otp and store in DB1 with TTL=5min
        otp = random.randint(1000, 9999)
        passcodes_table = dynamodb.Table('passcodes')
        ttl = int(time.time()) + 5 * 60
        passcodes_table.put_item(
            Item={
                'otp': otp,
                'faceId': faceId,
                'ttl': ttl
            }
        )

        # send otp to visitor's phone
        # try:
        # sns_response = sns.publish(
        #     PhoneNumber='+1'+phoneNumber,
        #     Message='Your one time passcode: ' + str(otp)
        # )
        # except:
        #     return {
        #         'statusCode': 200,
        #         'body': json.dumps('wrong phoneNumber')
        #     }

        return {
            'statusCode': 200,
            'body': json.dumps(
                'Success record!' + 'name: ' + name + ' phoneNumber: ' + phoneNumber + ' faceId: ' + faceId + ' random: ' + str(
                    otp))
        }
    except Exception as e:
        return {
            'statusCode': 200,
            'body': json.dumps(str(e))
        }
